package io.itit.ecp.admin.provide.action.controller;


import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.itit.ecp.admin.provide.action.req.PhysicalModelQueryReq;
import io.itit.ecp.admin.provide.action.resp.PhysicalModelResp;
import io.itit.ecp.admin.server.entity.PhysicalModelEntity;
import io.itit.ecp.admin.server.service.IPhysicalModelService;
import io.itit.grass.common.provide.action.req.BaseBatchIdReq;
import io.itit.grass.common.provide.action.req.BaseIdReq;
import io.itit.grass.common.provide.action.resp.ResultResp;
import io.itit.grass.common.provide.action.validation.IAdd;
import io.itit.grass.common.provide.action.validation.IQueryPage;
import io.itit.grass.common.provide.action.validation.IRequired;
import io.itit.grass.common.provide.action.validation.IUpdate;
import io.itit.grass.common.server.utils.ConvertUtils;
import io.itit.grass.web.wall.utils.PageUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;
import java.util.List;
import java.util.Objects;


/**
 * 物模型管理
 */
@RestController
@Api(tags = "物模型管理")
@RequiredArgsConstructor
@RequestMapping("/ecp-admin/physicalmodel")
public class PhysicalModelController {

    private final IPhysicalModelService physicalModelService;

    @ApiOperation("分页查询")
    @PostMapping("queryPage")
    @RequiresPermissions("ecp-admin:physicalmodel:search")
    public ResultResp<IPage<PhysicalModelResp>> queryPage(@RequestBody @Validated(IQueryPage.class) PhysicalModelQueryReq req) {
        Page<PhysicalModelEntity> page = physicalModelService.page(PageUtils.getPage(req, PhysicalModelEntity.class), buildQW(req));
        return ResultResp.success(ConvertUtils.convert(page, PhysicalModelResp.class));
    }

    @ApiOperation("不分页查询")
    @PostMapping("queryList")
    @RequiresPermissions("ecp-admin:physicalmodel:search")
    public ResultResp<List<PhysicalModelResp>> queryList(@RequestBody PhysicalModelQueryReq req) {
        List<PhysicalModelEntity> List = physicalModelService.list(buildQW(req));
        return ResultResp.success(ConvertUtils.convert(List, PhysicalModelResp.class));
    }


    @ApiOperation("详情")
    @PostMapping("detail")
    @RequiresPermissions("ecp-admin:physicalmodel:search")
    public ResultResp<PhysicalModelResp> detail(@RequestBody @Validated(IRequired.class) BaseIdReq req) {
        return ResultResp.success(ConvertUtils.copy(physicalModelService.getById(req.getId()), PhysicalModelResp.class));
    }

    @ApiOperation("详情")
    @PostMapping("detailByIds")
    @RequiresPermissions("ecp-admin:physicalmodel:search")
    public ResultResp<List<PhysicalModelResp>> detailByIds(@RequestBody @Validated(IRequired.class) BaseBatchIdReq req) {
        List<PhysicalModelEntity> list = physicalModelService.listByIds(req.getIds());
        return ResultResp.success(ConvertUtils.convert(list, PhysicalModelResp.class));
    }

    @ApiOperation("新增")
    @PostMapping("add")
    @RequiresPermissions("ecp-admin:physicalmodel:add")
    public ResultResp<Boolean> add(@RequestBody @Validated({IAdd.class}) PhysicalModelEntity req) {
        PhysicalModelEntity physicalModel = findByModelTag(req.getModelTag());
        if (Objects.nonNull(physicalModel)) {
            return ResultResp.fail("模型标识已存在:" + req.getModelTag());
        }
        return ResultResp.success(physicalModelService.saveOrUpdate(req));
    }

    private PhysicalModelEntity findByModelTag(String modelTag) {
        return physicalModelService.getOne(new LambdaQueryWrapper<PhysicalModelEntity>()
                .eq(PhysicalModelEntity::getModelTag, modelTag)
        );
    }

    @ApiOperation("编辑")
    @PostMapping("update")
    @RequiresPermissions("ecp-admin:physicalmodel:update")
    public ResultResp<Boolean> update(@RequestBody @Validated({IUpdate.class}) PhysicalModelEntity req) {
        PhysicalModelEntity physicalModel = findByModelTag(req.getModelTag());
        if (Objects.nonNull(physicalModel) && !physicalModel.getId().equals(req.getId())) {
            return ResultResp.fail("模型标识已存在:" + req.getModelTag());
        }
        return ResultResp.success(physicalModelService.updateById(req));
    }

    @ApiOperation("删除(根据Id删)")
    @PostMapping("deleteById")
    @RequiresPermissions("ecp-admin:physicalmodel:deleteById")
    public ResultResp<Boolean> deleteById(@RequestBody @Validated({IRequired.class}) BaseIdReq req) {
        return ResultResp.success(physicalModelService.removeById(req.getId()));
    }

    @ApiOperation("批量删除")
    @PostMapping("batchDelete")
    @RequiresPermissions("ecp-admin:physicalmodel:batchDelete")
    public ResultResp<Boolean> batchDelete(@RequestBody @Validated({IRequired.class}) BaseBatchIdReq req) {
        return ResultResp.success(physicalModelService.removeBatchByIds(req.getIds(), 1000));
    }

    private Wrapper<PhysicalModelEntity> buildQW(PhysicalModelQueryReq req) {
        LocalDateTime start = null;
        LocalDateTime end = null;
        if (StringUtils.hasLength(req.getCreateTm())) {
            LocalDate date = LocalDate.parse(req.getCreateTm(), DateTimeFormatter.ofPattern("MM/dd/yyyy"));
            start = date.atTime(LocalTime.MIN);
            end = date.atTime(LocalTime.MAX);
        }
        return Wrappers.<PhysicalModelEntity>lambdaQuery()
                .in(!CollectionUtils.isEmpty(req.getIds()), PhysicalModelEntity::getId, req.getIds())
                .eq(StringUtils.hasLength(req.getModelType()), PhysicalModelEntity::getModelType, req.getModelType())
                .eq(StringUtils.hasLength(req.getFieldType()), PhysicalModelEntity::getFieldType, req.getFieldType())
                .like(StringUtils.hasLength(req.getModelName()), PhysicalModelEntity::getModelName, req.getModelName())
                .like(StringUtils.hasLength(req.getModelTag()), PhysicalModelEntity::getModelTag, req.getModelTag())
                .ge(Objects.nonNull(start), PhysicalModelEntity::getCreateTm, start)
                .le(Objects.nonNull(end), PhysicalModelEntity::getCreateTm, end)
                .orderByDesc(PhysicalModelEntity::getCreateTm);
    }
}
